﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Sword.Data;

namespace Sword.ProxyCore.RuleMatcher
{
    /// <summary>
    /// 匹配类：匹配Http请求的目标URL部分
    /// </summary>
    public class UrlMatcher
    {
        public ConditionEnumType Type
        {
            get { return ConditionEnumType.Url; }
        }

        public bool IsMatch(Fiddler.Session oSession, ConditionItem rule)
        {
            
			
			if (rule.Expression.Trim().StartsWith("http"))
            {
                return MatchUrl(oSession.fullUrl, rule.Expression);
            }
            else
            {
                Uri url = new Uri(oSession.fullUrl);
                return MatchUrl(oSession.fullUrl, url.Scheme + "://" + rule.Expression);
            }
        }

        bool MatchUrl(string url, string expression)
        {
            if (string.IsNullOrEmpty(expression))
            {
                return false;
            }
            if (expression.IndexOf('*') > -1)
            {
                Regex matcher = new Regex(Regex.Escape(expression).Replace(@"\*", "*").Replace("*", ".*"), RegexOptions.IgnoreCase);
                return matcher.IsMatch(url);
            }
            else
            {
                Regex matcher = new Regex(Regex.Escape(expression), RegexOptions.IgnoreCase);
                return matcher.IsMatch(url);
            }

        }
    }
}
